from django import forms
from django.contrib.auth import get_user_model
from .models import CaptchaModel

User = get_user_model()

class signupForm(forms.Form):
    username = forms.CharField(max_length = 50, min_length = 1, error_messages = {
        'required': '需要填写用户名',
        'max_length': '用户名长度需在1到50之间',
        'min_length': '用户名长度需在1到50之间',
    })
    email = forms.EmailField(error_messages = {
        'required': '需要填写用户邮箱',
        'invalid': '请填写正确格式的邮箱',
    })
    captcha = forms.CharField(max_length = 4, min_length = 4)
    password = forms.CharField(max_length = 20, min_length = 6)

    def clean_email(self):
        email = self.cleaned_data.get('email')
        if User.objects.filter(email = email).exists():
            raise forms.ValidationError("该用户已经注册过")
        return email
    
    def clean_captcha(self):
        email = self.cleaned_data.get('email')
        captcha = self.cleaned_data.get('captcha')
        captcha_model = CaptchaModel.objects.filter(email = email, captcha = captcha).first()
        if not captcha_model:
            raise forms.ValidationError('验证码错误')
        captcha_model.delete()
        return captcha

class loginForm(forms.Form):
    email = forms.EmailField(error_messages = {
        'required': '需要填写用户邮箱',
        'invalid': '请填写正确格式的邮箱',
    })
    password = forms.CharField(max_length = 20, min_length = 6)
    remember = forms.IntegerField(required = False)